package TestPaperSystem.service.impl;

import TestPaperSystem.Dto.ExamDTO;
import TestPaperSystem.Dto.PageUtils_VO;
import TestPaperSystem.entity.Exam;
import TestPaperSystem.entity.ExamConfig;
import TestPaperSystem.entity.ExamRepo;
import TestPaperSystem.mapper.ExamRepoMapper;
import TestPaperSystem.service.ExamConfigService;
import TestPaperSystem.service.ExamRepoService;
import TestPaperSystem.service.ExamService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwj
 * @since 2023-03-25
 */
@Service
public class ExamRepoServiceImpl extends ServiceImpl<ExamRepoMapper, ExamRepo> implements ExamRepoService {

    @Autowired
    ExamService examService;

    @Resource
    ExamRepoMapper examRepoMapper;

    @Autowired
    ExamConfigService examConfigService;

    @Override
    public ExamDTO getByExamId(String examId) throws Exception{

        ExamDTO examDTO = new ExamDTO();

        QueryWrapper<ExamRepo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ExamRepo::getExamId,examId);
        ExamRepo examRepo = examRepoMapper.selectOne(queryWrapper);

        Exam exam = examService.getById(examId);

        BeanUtils.copyProperties(exam,examDTO);

        examDTO.getRepoList().add(examRepo);

        ExamConfig examConfig = examConfigService.getConfigByExamId(examId);

        examDTO.setExamConfig(examConfig);

        return examDTO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveData(ExamDTO examDTO) throws Exception {
        Exam exam = new Exam();

        BeanUtils.copyProperties(examDTO,exam);

        String id = String.valueOf(System.currentTimeMillis());

        if(examDTO.getId() == null){
            exam.setId(id);
            examDTO.getRepoList().get(0).setExamId(id);
            examDTO.getRepoList().get(0).setId(id);
            examDTO.getExamConfig().setExamId(id);
            return (this.saveBatch(examDTO.getRepoList()) & examService.save(exam) & examConfigService.saveData(examDTO.getExamConfig()));

        }else{

            return (this.updateBatchById(examDTO.getRepoList()) &
                    examService.update(exam,new UpdateWrapper<Exam>().lambda().eq(Exam::getId,exam.getId()))
                    & examConfigService.saveData(examDTO.getExamConfig()));

        }


    }
}
